<?php
namespace Admin\Controller;

use Admin\Controller\CommonController;

/**
 * 模块
 * @author wangdong
 */
class TaskController extends CommonController
{
    public function roads($draw = 1, $start = 0, $length = 10, $sort = 'status', $order = array(array('dir' => 'asc')))
    {
        //站点列表
        if (IS_POST) {
            $dbSite = M('Roads');
            $total = $dbSite->count();
            $list = array();
            if ($total > 0) {
                $order = $sort . ' ' . $order[0]['dir'];
                $limit = $start . "," . $length;
                $list = $dbSite->field("*,FROM_UNIXTIME(create_time, \"%Y-%m-%d %H:%i:%s\") as create_time")
                    ->limit($limit)
                    ->order($order)
                    ->select();
            }
            $data = array(
                "draw" => $draw,
                "recordsTotal" => $total,
                "recordsFiltered" => $total,
                "data" => $list
            );
            $this->ajaxReturn($data);
        } else {
            $this->display();
        }
    }

    public function index($draw = 1, $start = 0, $length = 10, $sort = 'id', $order = array(array('dir' => 'desc')))
    {
        //站点列表
        if (IS_POST) {
            $dbSite = M('Task');
            $roleid = session('roleid');
            $where = '1=1';
            if ($roleid != 1) {
                $siteid = session('siteid');
                $where .= ' and t.site_id=' . $siteid;
            }
            $total = $dbSite->table('__TASK__ t')->where($where)->count();
            $list = array();
            if ($total > 0) {

                $order = $sort . ' ' . $order[0]['dir'];
                $limit = $start . "," . $length;
                $list = $dbSite->table('__TASK__ t')
                    ->field("t.*,FROM_UNIXTIME(t.create_time, \"%Y-%m-%d %H:%i:%s\") as create_time,FROM_UNIXTIME(t.public_time, \"%m-%d %H:%i\") as public_time")
                    ->where($where)
                    ->limit($limit)
                    ->order($order)
                    ->select();
            }
            $data = array(
                "draw" => $draw,
                "recordsTotal" => $total,
                "recordsFiltered" => $total,
                "data" => $list
            );
            $this->ajaxReturn($data);
        } else {
            //放弃3分钟未接受的任务
            $dbTask = M('Task');
            $dbTask->where('status=1 and public_time<' . (time() - 180))->save(array('status' => 3, 'note' => '三分钟未处理,自动放弃任务'));
            $this->display();
        }
    }

    public function add()
    {
        if (IS_POST) {
            $taskdb = M('Task');
            $_validate = array(
                array('roads_id', 'require', '线路必须选择！'),
                array('total_load', 'require', '运输方量必须填写！'),
                //array('car_id', 'require', '运输车辆必须填写！'),
                array('load_site', 'require', '装料口必须填写！')
            );
            if (!$taskdb->validate($_validate)->create()) {
                // 如果创建失败 表示验证没有通过 输出错误提示信息
                $this->error($taskdb->getError());
            } else {
                $data = I('post.');
                //查询线路
                $roadsdb = M('Roads');
                $roads = $roadsdb->table('__ROADS__ r')->field('r.*,rd.distance,rd.duration')->join('left join __ROADS_DETAIL__ rd on r.id=rd.roads_id')->where('r.id=' . $data['roads_id'])->find();
                $data['site_id'] = $roads['site_id'];
                $data['task_from'] = $roads['task_from'];
                $data['task_from_longitude'] = $roads['task_from_longitude'];
                $data['task_from_latitude'] = $roads['task_from_latitude'];
                $data['task_from_mobile'] = $roads['site_mobile'];
                $data['task_end'] = $roads['task_end'];
                $data['task_end_longitude'] = $roads['task_end_longitude'];
                $data['task_end_latitude'] = $roads['task_end_latitude'];
                $data['distance'] = $roads['distance'];
                $data['duration'] = $roads['duration'];
                $data['linkman'] = $roads['linkman'];
                $data['mobile'] = $roads['mobile'];
                $data['cost_load'] = $data['total_load'];
                $cardb = M('Car');
                if($data['car_id']){
                    $car = $cardb->where('id=' . $data['car_id'])->find();
                    $data['car_name'] = $car['name'];
                    $data['car_no'] = $car['carno'];
                    $data['car_load'] = $car['load'];
    
                    if ($car['load'] > $data['cost_load']) {
                        //保底方量
                        $load_def = C('LOAD_DEF');
                        $d = explode(',', $load_def);
                        for ($i = 0; $i < count($d); $i++) {
                            $s = explode(':', $d[$i]);
                            if ($s[0] == $car['load']) {
                                if ($data['cost_load'] < $s[1]) {
                                    $data['cost_load'] = $s[1];
                                }
                                break;
                            }
                        }
                    }
                }
//                $data[''] = floor(($data['total_load'] - 1) / $car['load']) + 1;运输次数
                if (empty($data['id'])) {
                    unset($data['id']);
                    $data['orderno'] = date('mdHis') . rand(1000, 9999);
                    $data['status'] = 0;
                    $data['create_time'] = time();
                    $state = $taskdb->add($data);
                    $task_id=$state;
                    //$sort=car_sort($data['cost_load'],$data['site_id']);
                   $sort=car_sort();
                    $sort=json_encode($sort);
                   
                    $name = '循环任务';
                    $cmd = 'php abc.php';
                    $params = array(
                        'params'=>1
                    );
                    $timeOptions = array(
                        'minute'=>1
                    );
                    $this->add_loop_task($name,$cmd,$params,$timeOptions,$task_id,$sort);
                    
                    $state ? $this->success('添加成功') : $this->error('添加失败');
                } else {
                    $id = $data['id'];
                    unset($data['id']);
                    $task = $taskdb->where('id=' . $id)->find();
                    //释放车辆使用状态
//                    if($task['car_id']!=$data['car_id']){
//                        $cardb->where('id=' . $task['car_id'])->save(array('is_use'=>0));
//                        $cardb->where('id=' . $data['car_id'])->save(array('is_use'=>2,'use_time'=>time()));
//                    }
                    $state = $taskdb->where('id=' . $id)->save($data);
                    $state ? $this->success('修改成功') : $this->error('修改失败');
                }
            }
        } else {
            $id = I('get.id', 0);
            if ($id > 0) {
                $taskdb = M('Task');
                $task = $taskdb->where('id=' . $id)->find();
                $sitedb = M('Site');
                $site = $sitedb->where('id=' . $task['site_id'])->find();
                $copy = I('get.copy', 0);
                if ($copy == 1) {
                    unset($task['id']);
                    unset($task['car_name']);
                    unset($task['car_no']);
                    unset($task['car_id']);
                }
                $this->assign('site', $site);
                $this->assign('data', $task);
            }
            $task_load = C('CAR_LOAD');
            $this->assign('car_load', explode(',', $task_load));
            $this->display();
        }

    }


    public function addRoads()
    {
        if (IS_POST) {
            $taskdb = M('Roads');
            $_validate = array(
                array('site_id', 'require', '站点必须填写！'),
                array('site_mobile', 'require', '装料站联系电话必须填写！'),
                array('task_end', 'require', '抵达地址必须填写！'),
                array('linkman', 'require', '联系人必须填写'),
                array('mobile', 'require', '联系电话必须填写！'),
            );
            if (!$taskdb->validate($_validate)->create()) {
                // 如果创建失败 表示验证没有通过 输出错误提示信息
                $this->error($taskdb->getError());
            } else {
                $data = I('post.');
                $task_end_latgong = $data['task_end_latgong'];
                $lonlat = explode(",", $task_end_latgong);
                unset($data['lonlat']);
                $data['task_end_longitude'] = $lonlat[0];
                $data['task_end_latitude'] = $lonlat[1];
                //查询站点
                $sitedb = M('Site');
                $site = $sitedb->where('id=' . $data['site_id'])->find();
                $data['task_from'] = $site['name'];
                $data['task_from_longitude'] = $site['longitude'];
                $data['task_from_latitude'] = $site['latitude'];
                if (empty($data['id'])) {
                    unset($data['id']);
                    $data['number'] = date("mdHis");
                    $data['status'] = 0;
                    $data['create_time'] = time();
                    $state = $taskdb->add($data);

                    $state ? $this->success('添加成功') : $this->error('添加失败');
                } else {
                    $id = $data['id'];
                    unset($data['id']);
                    $state = $taskdb->where('id=' . $id)->save($data);
                    $state ? $this->success('修改成功') : $this->error('修改失败');
                }
            }
        } else {
            $id = I('get.id', 0);
            if ($id > 0) {
                $taskdb = M('Roads');
                $task = $taskdb->where('id=' . $id)->find();
                $this->assign('data', $task);
            }
//            $car_load = C('CAR_LOAD');
//            $this->assign('car_load',explode(',',$car_load));
            $this->display();
        }

    }

    public function task()
    {
        $this->display();
    }

    public function taskEnd()
    {
        $this->address = I('get.address');
        $this->lng = I('get.lng', 0);
        $this->lat = I('get.lat', 0);
        $this->display();
    }


    public function getRoads()
    {
        $id = I('get.id', 0);
        if ($id == 0) {
            return;
        }
        $roadsdetail = M('Roads_detail');
        $way = $roadsdetail->where('roads_id=' . $id)->find();
        if (!empty($way)) {
            $this->point = $way['point'];
        }
        $this->id = $id;
        $this->slng = I('get.slng', 0);
        $this->slat = I('get.slat', 0);
        $this->elng = I('get.elng', 0);
        $this->elat = I('get.elat', 0);
        $this->type = I('get.type', 0);
        $this->display();
    }

    public function loss()
    {
        if (IS_POST) {
            $id = I('post.id', 0);
            if ($id == 0) {
                return;
            }
            $taskdb = M('Task');
            $task = $taskdb->where('id=' . $id)->find();
            if (empty($task)) {
                $this->error('任务不存!');
            }
            $note = I('post.note', '系统选择放弃任务');
            $taskdb->where('id=' . $id)->save(array('status' => 3, 'note' => $note));
            $message = array(
                // 消息的标题.
                'title' => '您的任务已取消!',
                // 消息内容
                'description' => '后台已经取消任务',
                "custom_content"=> array("type"=>"2",'task_id'=>$id)
            );
            $cardb = M('Car');
            $car = $cardb->where('id=' . $task['car_id'])->find();
            if(empty($car['channel_id'])){
                $this->sendMsg($car['channel_id'],$message);
            }
            $this->success('放弃任务成功!');
        } else {
            $id = I('get.id', 0);
            if ($id == 0) {
                return;
            }
            $this->assign('id', $id);
            $this->display();
        }
    }

    public function finish()
    {
        if (IS_POST) {
            $id = I('post.id', 0);
            if ($id == 0) {
                return;
            }
            $taskdb = M('Task');
            $task = $taskdb->where('id=' . $id)->find();
            if (empty($task)) {
                $this->error('任务不存!');
            }
            $task_logdb = M('Task_log');
            $tlog = $task_logdb->where(array('task_id' => $id))->find();
            $logupdate = array('finish_time' => time());
            if (empty($tlog['return_time'])) {
                $logupdate['return_time'] = time();
            }
            if (empty($tlog['unload_finish_time'])) {
                $logupdate['unload_finish_time'] = time();
            }
            if (empty($tlog['arrived_time'])) {
                $logupdate['arrived_time'] = time();
                $logupdate['unloading_time'] = time();
            }
            if (empty($tlog['depature_time'])) {
                $logupdate['depature_time'] = time();
            }
            if (empty($tlog['load_time'])) {
                $logupdate['load_time'] = time();
            }
            $note = I('post.note', '系统选择完成');
            $task_logdb->where(array('task_id' => $id))->save($logupdate);
            $taskdb->where('id=' . $id)->save(array('status' => 4, 'note' => $note, 'step' => 7, 'finish_time' => time(), 'use_time' => 0));
            $this->success('完成任务!');
        } else {
            $id = I('get.id', 0);
            if ($id == 0) {
                return;
            }
            $this->assign('id', $id);
            $this->display();
        }
    }


    public function setWay()
    {
        $id = I('post.id', 0);
        $point = I('post.point', '');
        $distance = I('post.distance', '');
        $duration = I('post.duration', '');
        if ($id == 0) {
            $this->error('数据错误');
        }
        $taskdb = M('Roads');
        $task = $taskdb->where('id=' . $id . ' and status=0')->find();
        if (empty($task)) {
            $this->error('线路不存在或停用!');
        }
        $roadsdetail = M('Roads_detail');
        $roadsdetail->where('roads_id=' . $id)->delete();
        if (!empty($point)) {
            $point = trim($point, '|');
        }
        $distance = round($distance / 1000, 1); //转换为公里
        $duration = floor($duration / 60);//转换为分钟
//        $distance = str_replace("公里",'',$distance);
//        $duration = str_replace("分钟",'',$duration);
        $roadsdetail->add(array('roads_id' => $id, 'point' => $point, 'distance' => $distance, 'duration' => $duration));
        $this->success('线路规划成功');
    }


    public function sendToCar()
    {
        if (IS_POST) {
            //发送任务到相应车辆
            $id = I('post.id', 0);
            $taskdb = M('Task');
            $task = $taskdb->where('id=' . $id . ' and status=0')->find();
            if (empty($task)) {
                $this->error('任务不存在,或已经执行!');
            }
            $cardb = M('Car');
            $car = $cardb->where('id=' . $task['car_id'])->find();
            if (empty($car['channel_id'])) {
                $this->error('车辆未登录,无法接收任务!');
            }

            //发送通知
            require_once APP_PATH . "Common/Lib/push/sdk.php";
            $message = array(
                // 消息的标题.
                'title' => '有一个新任务，请注意查看',
                // 消息内容
                'description' => "运输：" . $task['task_from'] . '到' . $task['task_end'] . $task['total_load'] . '方',
                "custom_content"=> array("type"=>"1",'task_id'=>$id)
            );
            // 设置消息类型为 通知类型.
            $opts = array(
                'msg_type' => 1
            );

            // 创建SDK对象.
            $sdk = new \PushSDK();
            // 向目标设备发送一条消息
            $rs = $sdk->pushMsgToSingleDevice($car['channel_id'], $message, $opts);
            // 判断返回值,当发送失败时, $rs的结果为false, 可以通过getError来获得错误信息.
            if ($rs === false) {
//                print_r($sdk->getLastErrorCode());
//                print_r($sdk->getLastErrorMsg());
                $this->error('发送任务失败!错误:' . $sdk->getLastErrorCode() . '  描述:' . $sdk->getLastErrorMsg());
            } else {
                // 将打印出消息的id,发送时间等相关信息.
//                print_r($rs);
                $taskdb->where('id=' . $id . ' and status=0')->save(array('status' => 1, 'public_time' => time()));

                //添加任务执行日志
                $task_logdb = M('Task_log');
                $task_logdb->add(array('task_id' => $id, 'car_id' => $task['car_id'], 'public_time' => time()));
            }
//            $cardb = M("Car");
//            $cardb->where('id=' . $task['car_id'] . ' and status=0')->save(array('is_use'=>1,'use_time'=>time()));
            $this->success('发送任务成功!');
        } else {
            $id = I('get.id', 0);
            if ($id > 0) {
                $taskdb = M('Task');
                $task = $taskdb->where('id=' . $id)->find();
                $this->assign('data', $task);
                $taskwaydb = M('Roads_detail');
                $way = $taskwaydb->where('roads_id=' . $task['roads_id'])->find();
                if (empty($way)) {
                    echo "<div style='padding: 20px 0px;text-align: center;'>请先规划线路</div>";
                    exit();
                }
            }
            $this->display();
        }
    }

    function roadsSearch($key = '', $page = 1)
    {
        $db = M();
        $where = "1=1  and r.status=0";
        if (!empty($key)) {
            $where .= ' and (number like \'%' . $key . '%\' or task_from like \'%' . $key . '%\' or task_end like \'%' . $key . '%\')';
        }
        $roleid = session('roleid');
        if ($roleid != 1) {
            $siteid = session('siteid');
            $where .= ' and r.site_id=' . $siteid;
        }
        $total = $db->table("__ROADS__ r")->join("LEFT JOIN __SITE__ s on r.site_id=s.id")->where($where)->count();
        $order = 'create_time desc';
        $limit = ($page - 1) * 30 . "," . 30;
        $list = $db->table("__ROADS__ r")->field('r.id,task_from,task_from_longitude,task_from_latitude,task_end,s.load_num')
            ->join("LEFT JOIN __SITE__ s on r.site_id=s.id")
            ->where($where)->order($order)->limit($limit)->select();
        $list = empty($list) ? array() : $list;
        $data = array(
            "total_count" => $total,
            "items" => $list
        );
        $this->ajaxReturn($data);
    }

    public function getCar($draw = 1, $start = 0, $length = 10)
    {
        if (IS_POST) {
            $load = I('get.load');
            $roadsid = I('get.roadsid');
            $roadsDB = M('Roads');
            $roads = $roadsDB->where('id=' . $roadsid)->find();
            $long = $roads['task_from_longitude'];
            $lat = $roads['task_from_latitude'];
            $now = time();
            $endTime = time() - (7 * 24 * 3600);
            $starttime = I('get.start');
            if ($starttime != '') {
                $starttime = str_replace("年", '-', str_replace("月", '-', str_replace("日", '', $starttime)));
                $now = strtotime($starttime . " 00:00:00");
                $endTime = $now - (7 * 24 * 3600);
            }
            $endtime = I('get.end');
            if ($endtime != '') {
                $endtime = str_replace("年", '-', str_replace("月", '-', str_replace("日", '', $endtime)));
                $endTime = strtotime($endtime . " 23:59:59");
            }
            $db = M();
            $where = " c.id not in  (select car_id from " . C('DB_PREFIX') . "task t where (t.status=0 or t.status=1 or t.status=2) or (t.public_time>" . (time() - 180) . " and t.status=1))  and c.status=0 and c.work_status=1 and c.load>=" . $load;
            $roleid = session('roleid');
            if ($roleid != 1) {
                $siteid = session('siteid');
                $where .= ' and (c.site=' . $siteid . ' or c.site=0)';
            }
            $total = $db->table('__CAR__ c')->where($where)->count();
            $limit = $start . "," . $length;

            $list = $db->table('__CAR__ c')->field('c.*,ts.number,tc.tadiao,bs.bengsong,zx.zhixie,dx.douxie,tu.total_time,FROM_UNIXTIME(tf.finish_time, "%m-%d %H:%i") as finish_time,
            (ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-c.latitude*PI()/180)/2),2)+COS(' . $lat .
                '*PI()/180)*COS(c.latitude*PI()/180)*POW(SIN((' . $long . '*PI()/180-c.longitude*PI()/180)/2),2)))*1000)) AS dis')
                ->join("left join (select count(*) as tadiao,car_id from __TASK__ where public_time<= " . $now . " and public_time>=" . $endTime . " and unload_type=1 and status= 4 group by car_id) tc  on c.id=tc.car_id")
                ->join("left join (select count(*) as number,car_id from __TASK__ where public_time<= " . $now . " and public_time>=" . $endTime . "  and status= 4 group by car_id) ts  on c.id=ts.car_id")
                ->join("left join (select count(*) as bengsong,car_id from __TASK__ where public_time<= " . $now . " and public_time>=" . $endTime . " and unload_type=0  and status= 4 group by car_id) bs  on c.id=bs.car_id")
                ->join("left join (select count(*) as zhixie,car_id from __TASK__ where public_time<= " . $now . " and public_time>=" . $endTime . " and unload_type=2  and status= 4 group by car_id) zx  on c.id=zx.car_id")
                ->join("left join (select count(*) as douxie,car_id from __TASK__ where public_time<= " . $now . " and public_time>=" . $endTime . " and unload_type=3  and status= 4 group by car_id) dx  on c.id=dx.car_id")
                ->join("left join (select sum(use_time) as total_time,car_id from __TASK__ where public_time<= " . $now . " and public_time>=" . $endTime . "  and status= 4 group by car_id) tu  on c.id=tu.car_id")
                ->join("left join (select finish_time,car_id from __TASK__ where status= 4 and finish_time >0 group by car_id order by finish_time desc ) tf  on c.id=tf.car_id  ")
                ->where($where)->limit($limit)->order('tf.finish_time desc,c.online desc,tu.total_time asc,ts.number asc,tc.tadiao desc')->group('c.id')->select();
            $list = empty($list) ? array() : $list;
            $data = array(
                "draw" => $draw,
                "recordsTotal" => $total,
                "recordsFiltered" => $total,
                "data" => $list
            );
            $this->ajaxReturn($data, 'json');
        } else {
            $this->lng = I('get.lng', 0);
            $this->lat = I('get.lat', 0);
            $this->roadsid = I('get.roadsid');
            $this->load = I('get.load', 0);
            $this->start = date("Y年m月d日");
            $this->end = date("Y年m月d日", time() - (7 * 24 * 3600));
            $this->display();
        }

    }

    public function order($draw = 1, $start = 0, $length = 10, $sort = 'id', $order = array(array('dir' => 'desc')), $report = array())
    {
        //站点列表
        if (IS_POST) {
            $where = "1=1";
            if (!empty($report['task_from'])) {
                $where .= ' and (t.task_from like \'%' . $report['task_from'] . '%\')';
            }
            if (!empty($report['task_end'])) {
                $where .= ' and (t.task_end like \'%' . $report['task_end'] . '%\')';
            }
            $starttime = $report['start'];
            if ($starttime != '') {
                $starttime = str_replace("年", '-', str_replace("月", '-', str_replace("日", '', $starttime)));
                $where .= ' and t.public_time>=' . strtotime($starttime . " 00:00:00");
            }
            $endtime = $report['end'];
            if ($endtime != '') {
                $endtime = str_replace("年", '-', str_replace("月", '-', str_replace("日", '', $endtime)));
                $where .= ' and  t.public_time<=' . strtotime($endtime . " 23:59:59");
            }
            if (isset($report['status']) && $report['status'] > -1) {
                $where .= ' and (t.status =  ' . $report['status'] . ')';
            }
            $dbSite = M();
            $total = $dbSite->table("__TASK__ t")->where($where)->count();
            $list = array();
            if ($total > 0) {
                $order = $sort . ' ' . $order[0]['dir'];
                $limit = $start . "," . $length;
                $list = $dbSite->table("__TASK__ t")->field("t.*,
                FROM_UNIXTIME(t.create_time, \"%Y-%m-%d %H:%i:%s\") as create_time,
                FROM_UNIXTIME(t.public_time, \"%m-%d %H:%i\") as public_time,
                FROM_UNIXTIME(tl.start_time,\"%m-%d %H:%i\") as start_time,
                FROM_UNIXTIME(tl.load_time, \"%m-%d %H:%i\") as load_time,
                FROM_UNIXTIME(tl.depature_time ,\"%m-%d %H:%i\") as depature_time,
                FROM_UNIXTIME(tl.arrived_time ,\"%m-%d %H:%i\") as arrived_time,
                FROM_UNIXTIME(tl.unloading_time,\"%m-%d %H:%i\") as unloading_time,
                FROM_UNIXTIME(tl.finish_time, \"%m-%d %H:%i\") as finish_time")
                    ->join("LEFT JOIN __TASK_LOG__ tl on t.id=tl.task_id")
                    ->limit($limit)
                    ->where($where)
                    ->order($order)
                    ->select();
            }
            $data = array(
                "draw" => $draw,
                "recordsTotal" => $total,
                "recordsFiltered" => $total,
                "data" => $list
            );
            $this->ajaxReturn($data);
        } else {
            $this->display();
        }
    }

    public function export_order_data($report)
    {

        $where = "1=1";
        $title = "";
        if (!empty($report['task_from'])) {
            $where .= ' and (t.task_from like \'%' . $report['task_from'] . '%\')';
        }
        if (!empty($report['task_end'])) {
            $where .= ' and (t.task_end like \'%' . $report['task_end'] . '%\')';
        }
        $starttime = $report['start'];
        if ($starttime != '') {
            $title .= $starttime;
            $starttime = str_replace("年", '-', str_replace("月", '-', str_replace("日", '', $starttime)));
            $where .= ' and t.public_time>=' . strtotime($starttime . " 00:00:00");
        }
        $endtime = $report['end'];
        if ($endtime != '') {
            if (!empty($title)) {
                $title .= "-";
            }
            $title .= $endtime;
            $endtime = str_replace("年", '-', str_replace("月", '-', str_replace("日", '', $endtime)));
            $where .= ' and  t.public_time<=' . strtotime($endtime . " 23:59:59");
        }
        if (isset($report['status']) && $report['status'] > -1) {
            $where .= ' and (t.status =  ' . $report['status'] . ')';
        }
        $dbSite = M();
        $list = $dbSite->table("__TASK__ t")->field("t.*,
                FROM_UNIXTIME(t.create_time, \"%Y-%m-%d %H:%i:%s\") as create_time,
                FROM_UNIXTIME(t.public_time, \"%Y-%m-%d %H:%i:%s\") as public_time,
                FROM_UNIXTIME(tl.start_time,\"%Y-%m-%d %H:%i:%s\") as start_time,
                FROM_UNIXTIME(tl.load_time, \"%Y-%m-%d %H:%i:%s\") as load_time,
                FROM_UNIXTIME(tl.depature_time ,\"%Y-%m-%d %H:%i:%s\") as depature_time,
                FROM_UNIXTIME(tl.arrived_time ,\"%Y-%m-%d %H:%i:%s\") as arrived_time,
                FROM_UNIXTIME(tl.unloading_time,\"%Y-%m-%d %H:%i:%s\") as unloading_time,
                 FROM_UNIXTIME(tl.unloading_time,\"%Y-%m-%d %H:%i:%s\") as unload_finish_time,
                 FROM_UNIXTIME(tl.return_time, \"%Y-%m-%d %H:%i:%s\") as return_time,
                FROM_UNIXTIME(tl.finish_time, \"%Y-%m-%d %H:%i:%s\") as finish_time")
            ->join("LEFT JOIN __TASK_LOG__ tl on t.id=tl.task_id")
            ->where($where)
            ->order('t.public_time asc')
            ->select();
        $list = empty($list) ? array() : $list;
        require_once APP_PATH . "Common/Lib/PHPExcel18/PHPExcel.php";
        $objPHPExcel = new \PHPExcel();

        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(25);

        //设置行高度
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(30);

        //set font size bold
        $objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(16);
        $objPHPExcel->getActiveSheet()->getStyle('A2:R2')->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(22);
        $objPHPExcel->getActiveSheet()->getStyle('A2:R2')->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
        //设置水平居中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A:R')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
//        $objPHPExcel->getActiveSheet()->getStyle('F')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
//
        //合并cell
        $objPHPExcel->getActiveSheet()->mergeCells('A1:R1');
//        for ($i = 0; $i < count($list); $i++) {
        foreach ($list as $i => $val) {
            $objPHPExcel->getActiveSheet(0)->setCellValue('A' . ($i + 3), $val['task_from']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('B' . ($i + 3), $val['load_site']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('C' . ($i + 3), $val['task_end']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('D' . ($i + 3), $val['car_no']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('E' . ($i + 3), $val['car_name']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('F' . ($i + 3), $val['total_load']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('G' . ($i + 3), $val['grade']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('H' . ($i + 3), $val['components']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('I' . ($i + 3), $val['cost_load']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('J' . ($i + 3), $val['public_time']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('K' . ($i + 3), $val['start_time']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('L' . ($i + 3), $val['load_time']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('M' . ($i + 3), $val['depature_time']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('N' . ($i + 3), $val['unloading_time']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('O' . ($i + 3), $val['unload_finish_time']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('P' . ($i + 3), $val['return_time']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('Q' . ($i + 3), $val['finish_time']);
            if ($val['status'] == 0) {
                $status = "待开始";
            } else if ($val['status'] == 1) {
                $status = "待执行";
            } else if ($val['status'] == 2) {
                $status = '执行中';
            } else if ($val['status'] == 3) {
                $status = '放弃,' . $val['note'];
            } else if ($val['status'] == 4) {
                $note = "";
                if (!empty($val['note'])) {
                    $note = "  说明:" . $val['note'];
                }
                $status = '完成' . $note;
            }
            $objPHPExcel->getActiveSheet(0)->setCellValue('R' . ($i + 3), $status);

            $objPHPExcel->getActiveSheet()->getRowDimension($i + 3)->setRowHeight(20);
            $objPHPExcel->getActiveSheet()->getStyle('A' . ($i + 3) . ':R' . ($i + 3))->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
        }
//        if (count($list) > 0) {
//            $objPHPExcel->getActiveSheet()->mergeCells('A' . (count($list) + 3).':D' . (count($list) + 3));
//            $objPHPExcel->getActiveSheet(0)->getStyle('A'. (count($list) + 3))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
//            $objPHPExcel->getActiveSheet(0)->setCellValue('A' . (count($list) + 3), '合计');
////            $objPHPExcel->getActiveSheet(0)->setCellValue('B' . (count($list) + 3), '=SUM(B3:B' . (count($list) + 2) . ')');
//            $objPHPExcel->getActiveSheet(0)->setCellValue('E' . (count($list) + 3), '= SUM(E3:E' . (count($list) + 2) . ')');
////            $objPHPExcel->getActiveSheet(0)->setCellValue('D' . (count($list) + 3), '=SUM(D3:D' . (count($list) + 2) . ')');
//            $objPHPExcel->getActiveSheet()->getRowDimension(count($list) + 3)->setRowHeight(20);
//            $objPHPExcel->getActiveSheet()->getStyle('A' . (count($list) + 3) . ':G' . (count($list) + 3))->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
//        }
        $title .= '任务数据报表';
        // set table header content
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', $title)
            ->setCellValue('A2', '装料站')
            ->setCellValue('B2', '装料口')
            ->setCellValue('C2', '抵达地址')
            ->setCellValue('D2', '车号')
            ->setCellValue('E2', '司机')
            ->setCellValue('F2', '方量')
            ->setCellValue('G2', '标号')
            ->setCellValue('H2', '施工部位')
            ->setCellValue('I2', '保底')
            ->setCellValue('J2', '下达时间')
            ->setCellValue('K2', '接受时间')
            ->setCellValue('L2', '装料时间')
            ->setCellValue('M2', '发车时间')
            ->setCellValue('N2', '卸料开始')
            ->setCellValue('O2', '卸料结束')
            ->setCellValue('P2', '返回时间')
            ->setCellValue('Q2', '完成时间')
            ->setCellValue('R2', '状态');
        //  sheet命名
        $objPHPExcel->getActiveSheet()->setTitle("任务数据报表");

        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);
        // excel头参数
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $title . '(' . date('Ymd') . ').xls"');  //日期为文件名后缀
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  //excel5为xls格式，excel2007为xlsx格式
        $objWriter->save('php://output');
    }
    
    /**
     * 增加循环任务。
     * 每天执行：day 1 hour 0 minute 0 每天零点执行
     * 每小时执行：day 0 hour 1 minute 5 每小时的5分执行
     * 每隔若干分钟执行：day 0 hour 0 minute 5 每隔5分钟执行
     * @param $name
     * @param $cmd
     * @param $params
     * @param $timeOptions
     * @return mixed
     */
    public function add_loop_task($name,$cmd,$params,$timeOptions,$task_id,$sort){
       
        $nextrun = task_get_loop_nextrun($timeOptions);
        $asyntask=M('asyntask');
        $task = array(
            'available'=>1,
            'type'=>'loop',
            'name'=>$name,
            'cmd' => $cmd,
            'params'=> encode_params($params),
            'lastrun' => 0,
            'nextrun' => $nextrun,
            'task_id'=>$task_id,
            'sort'=>$sort
        );
        $task = array_merge($task,$timeOptions);
        return $asyntask->add($task);
        
    }

}